package cn.xiaolang.issue.support;

import lombok.extern.slf4j.Slf4j;

/**
 * 死锁示例
 *
 * @author fuhw/Dean
 * @date 2019-07-11
 */
@Slf4j
public class DeadLockDemo {

    // 资源1
    private static Object r1 = new Object();
    // 资源2
    private static Object r2 = new Object();

    public static void main(String[] args) {

        LockA a = new LockA();
        // A线程 锁 r1 r2
        new Thread(a, "LockA").start();
        // B线程 锁 r2 r1
        LockB b = new LockB();
        new Thread(b, "LockB").start();


    }

    static class LockA implements Runnable {

        @Override
        public void run() {
            while (true) {
                synchronized (r1) {
                    log.info("{}-抢到了-{}", Thread.currentThread().getName(), r1);
                    synchronized (r2) {
                        log.info("{}-抢到了-{}", Thread.currentThread().getName(), r2);
                    }
                }
            }
        }


    }

    static class LockB implements Runnable {

        @Override
        public void run() {
            while (true) {
                synchronized (r2) {
                    log.info("{}-抢到了-{}", Thread.currentThread().getName(), r2);
                    synchronized (r1) {
                        log.info("{}-抢到了-{}", Thread.currentThread().getName(), r1);
                    }
                }
            }
        }
    }

}